<?php
/**
* 保存海报上传的文件
* @author xiongfangwei 
* @since v1.0
* @modify 2015.6.21
* @copyright 深圳亿游
*/
require_once('root.con.php');
require_once(ROOT_PATH.'model/imagefile.model.php');


class fileCon extends rootCon {

	public function editorAction(){
		error_reporting(E_ALL);
		$from = r('from');
		$home = myrequest::getDomainUrl($from);
		if(mysafe::isWhiteDomain($from)){
			header('Access-Control-Allow-Origin:'.$home); //设置http://www.baidu.com允许跨域访问
			header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With'); //设置允许的跨域header
			header("X-Frame-Options: ALLOW-FROM ".$home); // 即使使用 127.0.0.1/a.php，也能显示b.php
		}
		header("Content-Type: text/html; charset=utf-8");

		$CONFIG = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents(ROOT_PATH."lib//ueditor/config.json")), true);
		$action = $_GET['action'];

		switch ($action) {
			case 'config':
				$result =  json_encode($CONFIG);
				break;

			/* 上传图片 */
			case 'uploadimage':
				/* 上传涂鸦 */
			case 'uploadscrawl':
				/* 上传视频 */
			case 'uploadvideo':
				/* 上传文件 */
			case 'uploadfile':
				$result = include(ROOT_PATH."/lib/ueditor/action_upload.php");
				break;

			/* 列出图片 */
			case 'listimage':
				$result = include(ROOT_PATH."/lib/ueditor/action_list.php");
				break;
			/* 列出文件 */
			case 'listfile':
				$result = include(ROOT_PATH."/lib/ueditor/action_list.php");
				break;

			/* 抓取远程文件 */
			case 'catchimage':
				$result = include(ROOT_PATH."/lib/ueditor/action_crawler.php");
				break;

			default:
				$result = json_encode(array(
						'state'=> '请求地址出错'
				));
				break;
		}

		/* 输出结果 */
		if (isset($_GET["callback"])) {
			if (preg_match("/^[\w_]+$/", $_GET["callback"])) {
				die(htmlspecialchars($_GET["callback"]) . '(' . $result . ')' ) ;
			} else {
				die(json_encode(array(
						'state'=> 'callback参数不合法'
				)));
			}
		}

		//iframe跨域显示内容解决
		$result = urlsafe_b64encode($result);
		header('Location: '.$home.'upload,show?rec='.$result);
	}


	//@todo 检查登录状态
	public function saveAction(){
		header("Access-Control-Allow-Methods:POST,GET");
		if(strtoupper($_SERVER['REQUEST_METHOD']) == 'OPTIONS'){
			exit;
		}

		$uid = mylogin::getUid();
		$imageFile = new ImageFile();
		//匹配出图片的格式,保存base64字符串为图片
		if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $_POST['data'], $result)){
              $type = $result[2];
              
              if($type=='php' || $type=='js' || $type=='html' || $type=='htm' || $type=='css'  ){
				  $this->j(-2,"格式错误!");
              }

			 $fileName = $uid.'_'.time();

              $newFile = "$fileName.{$type}";
              if (file_put_contents(UPLOAD_DIR."/".$newFile, base64_decode(str_replace($result[1], '', $_POST['data'])))){
				  $imageFile->load();
				  $imageFile->uid = $uid;
                  $imageFile->imagePos = p('imagePos');
				  $imageFile->uploadImg = "up/".$newFile;
				  $imageFile->ip = myrequest::getIP();
				  $imageFile->insertD = date('Y-m-d H:i:s');
				  $imageFile->save();
				  if(!IS_LINUX){
					  $imageFile->arr['dir'] = UPLOAD_DIR.$newFile;
				  }
				  $this->j(0,'上传成功',$imageFile->arr);
              }else{
                    $this->j(-1,'保存失败!');
              }
		}

		$this->j(-2,"格式错误");
		
	}

	public function delAction(){
		$fid = intval(r('fid'));
		$uid = mylogin::getUid();
		$imageFile = new ImageFile();
		$find = $imageFile->find([['uid'=>$uid],['fid'=>$fid]]);
		if($find){
			@unlink(ROOT_PATH.'/web/'.$imageFile->uploadImg);
			$imageFile->query('DELETE FROM tbl_image_file WHERE imageFileId= '.$fid);
			$this->j(0,'删除成功');
		}else{
			$this->j(-1,'删除失败');
		}

	}

	
	//@todo 检查登录状态
	public function cutAction(){
		require_once(ROOT_PATH.'model/user.model.php');

		$expire = time()+3600*24*365*10;
		$time = time();
		
		//------非法用户检测，没有登录重新登录---------
        $db = new mydb();
		$userRow = $db->getOne('SELECT FUserId FROM tbl_user WHERE FRandId="'.mylogin::getRandId().'"');
        $uid =  intval($userRow['FUserId']);
		
		$filename = ROOT_PATH.'/view/'.p('imgName');
		$to_File = ROOT_PATH.'/view/s'.p('imgName');
		$to_File2 = ROOT_PATH.'/view/ws'.p('imgName');

		/*读取图片 */
		$im = imagecreatefromjpeg($filename);

		/* 图片要截多少, 长/宽 */
		$src_w = p('imgWidth')/p('imgScale');
		$src_h = p('imgHeight')/p('imgScale');
		
		$src_x = p('imgX')/p('imgScale');
		$src_y = p('imgY')/p('imgScale');
		
		$dst_w = p('imgWidth'); //这里其实要计算一下的，跟进scale
		$dst_h = p('imgHeight');
		

		/* 先建立一个 新的空白图片档 */
		$newim = imagecreatetruecolor($dst_w, $dst_h);

		// 输出图要从哪边开始x, y , 原始图要从哪边开始 x, y , 要输多大 x, y(resize) , 要抓多大 x, y
		//http://php.net/manual/zh/function.imagecopyresampled.php
		//bool imagecopyresampled ( resource $dst_image , resource $src_image , int $dst_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h )
		imagecopyresampled($newim, $im, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);

		/* 放大 成 500 x 500 的图 */
		//imagecopyresampled($newim, $im, 0, 0, 100, 30, 500, 500, $new_img_width, $new_img_height);

		/* 将图印出来 */
		//$file = imagejpeg($newim,'',100);
		
		/* 保存图片 */
		//imageinterlace($newim, 1);//模糊到清晰展示
		imagepng ($newim,$to_File,0);
		
		/* 资源回收 */
		imagedestroy($newim);
		
		
		/* 微信分享小图片 新的空白图片档 */
		$dst_w = 100;
		$dst_h = 100;
		$newim = imagecreatetruecolor($dst_w, $dst_h);
		imagecopyresampled($newim, $im, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
		imagepng ($newim,$to_File2,0);
		/* 资源回收 */
		imagedestroy($newim);
		
		
		imagedestroy($im);
		
		
		//更新数据库
		$newFile = $_POST['imgName'];
		$arr = array(
			'FUploadImg'=>$newFile,
			'FName'=>p('name'),
			'FAddr'=>p('address'),
			'FAge'=>p('age'),
			'FComment'=>p('comment'),
			'FPhone'=>p('phone'),
			'FIsShared' =>intval(p('wordNum'))
		);
				
		$db->update('tbl_user',$arr,'FUserId='.$uid);

		
		die($newFile);
		
	}


}

